package com.ruoyi.service.company.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.enums.YesNoEnum;
import com.ruoyi.service.company.entity.CompanyEntity;
import com.ruoyi.service.company.enums.CheckStatusEnum;
import com.ruoyi.service.company.mapper.CompanyMapper;
import com.ruoyi.service.company.query.CompanyBaseQuery;
import com.ruoyi.service.company.service.CompanyService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 公司注册信息表 服务实现类
 * </p>
 *
 * @author Zane
 * @since 2025-10-04
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyEntity> implements
    CompanyService {

  @Override
  public boolean companyExist(String usci) {
    final LambdaQueryWrapper<CompanyEntity> query = effectQuery().eq(CompanyEntity::getUsci, usci);
    return this.baseMapper.selectCount(query) > 0;
  }

  @Override
  public CompanyEntity getByManager(Long userId) {
    final LambdaQueryWrapper<CompanyEntity> effectQuery = effectQuery()
        .eq(CompanyEntity::getManager, userId);
    return this.getOne(effectQuery);
  }

  @Override
  public String getNameById(Long comId) {
    return Optional.ofNullable(this.getById(comId)).map(CompanyEntity::getComName).orElse(null);
  }

  @Override
  public Long countCompany() {
    return count(effectQuery().eq(CompanyEntity::getStatus, CheckStatusEnum.PASSED.getCode()));
  }

  @Override
  public Long getCompanyApproval() {
    return count(effectQuery().eq(CompanyEntity::getStatus, CheckStatusEnum.CHECKING.getCode()));
  }

  @Override
  public List<CompanyEntity> selectListNeedCheck(CompanyBaseQuery query) {
    return list(effectQuery()
        .eq(CompanyEntity::getStatus, CheckStatusEnum.CHECKING.getCode())
        .orderByAsc(CompanyEntity::getComId)
    );
  }

  @Override
  public Map<Long, CompanyEntity> getMapByIds(List<Long> ids) {
    if (CollUtil.isEmpty(ids)) {
      return new HashMap<>();
    }
    return Optional.ofNullable(listByIds(ids)).orElseGet(ArrayList::new).stream().collect(
        Collectors.toMap(CompanyEntity::getComId, v -> v, (v1, v2) -> v1));
  }

  private LambdaQueryWrapper<CompanyEntity> effectQuery() {
    return new LambdaQueryWrapper<CompanyEntity>().eq(CompanyEntity::getDelFlag,
        YesNoEnum.NO.getCode());
  }
}
